//
//  WCDom.m
//  WebExtractSimpleViewer
//
//  Created by Daniel Braun on 10/03/07.
//  Copyright 2007 Daniel Braun http://page-appart.net, http://braun.daniel.free.fr All rights reserved.
//

#import "WCDom.h"
#ifdef NODOM
@implementation NSArray (DomCompatibility)
- (id) item:(int)idx
{
	int l=[self count];
	if (idx<0) return nil;
	if (idx>=l) return nil;
	return [self objectAtIndex:idx];
}
@end

@implementation NSXMLElement (DomCompatibility)

- (NSString *) idName
{
	NSXMLNode *at=[self attributeForName:@"id"];
	return [at stringValue];
}
- (NSString *) className
{
	NSXMLNode *at=[self attributeForName:@"class"];
	return [at stringValue];
}
- (NSString *) tagName
{
	return [self nodeName];
}

- (NSString *) getAttribute:(NSString *)n
{
	NSXMLNode *a=[self attributeForName:n];
	return [a stringValue];
}

- (NSString *) innerText
{
	return [self stringValue]; //XXX better implementation needed 
}
- (NSString *) outerHTML
{
	return [self description]; //XXX better implementation needed 
}
- (DOMNodeList *)getElementsByTagName:(NSString *)name
{
	int count=[self childCount];
	NSMutableArray *r=[NSMutableArray arrayWithCapacity:10];
	name=[name lowercaseString];
	int i;
	for (i=0; i<count; i++) {
		NSXMLNode *nod=[self childAtIndex:i];
		if ([[[nod nodeName]lowercaseString] isEqualToString:name]) {
			[r addObject:nod];
		}
	}
	return r;
}
@end

@implementation NSXMLNode (DomCompatibility)

- (NSXMLNode *) parentNode
{
	return [self parent];
}
- (NSXMLNode *) firstChild
{
	return [self childAtIndex:0];
}

- (NSString *) nodeName
{
	switch ([self kind]) {
		case NSXMLTextKind:
			return @"#text";
		case NSXMLElementKind:
			return [self name];
		case NSXMLCommentKind:
			return @"#comment";
		default:
			NSAssert(0, @"plaf");
			break;
	}
	return nil;
}
- (NSString *) nodeValue
{
	return [self description];
}

- (BOOL) hasChildNodes
{
	return [self childCount] ? YES : NO;
}

@end

#endif
